package service

import (
	"errors"
	"login-server/config"
	"login-server/model"
	"login-server/utils"
)

type UserService struct{}

func (s *UserService) Register(username, password, nickname string) error {
	var existUser model.User
	result := config.DB.Where("username = ?", username).First(&existUser)
	if result.RowsAffected > 0 {
		return errors.New("username already exists")
	}

	hashedPassword, err := utils.HashPassword(password)
	if err != nil {
		return err
	}

	user := model.User{
		Username: username,
		Password: hashedPassword,
		Nickname: nickname,
	}

	return config.DB.Create(&user).Error
}

func (s *UserService) Login(username, password string) (*model.User, error) {
	var user model.User
	result := config.DB.Where("username = ?", username).First(&user)
	if result.Error != nil {
		return nil, errors.New("user not found")
	}

	if !utils.CheckPasswordHash(password, user.Password) {
		return nil, errors.New("invalid password")
	}

	return &user, nil
}
